package cn.ulc.common.util;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.ulc.common.util.BaiduTTS.ConnUtil;
import cn.ulc.common.util.BaiduTTS.TokenHolder;

import java.io.File;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;

public class BaiDuTTSHelper {

  private static final Log log = LogFactory.get();
  final static String appKey = "WEnQniY85KzjMl9xoG5GQkTq";
  final static String secretKey = "oOMggcIKqYjMQpKXlS39L27cSLKlLxeR";

  // 发音人选择, 0为普通女声，1为普通男生，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女声
  private final static int per = 0;
  // 语速，取值0-15，默认为5中语速
  private final static int spd = 5;
  // 音调，取值0-15，默认为5中语调
  private final static int pit = 5;
  // 音量，取值0-9，默认为5中音量
  private final static int vol = 5;

  // 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav
  private final static int aue = 3;

  public final static String url = "http://tsn.baidu.com/text2audio"; // 可以使用https

  private static String cuid = "34f32F3FSF34gdERG4S";

  public static String getMp3(String orderNumber, BigDecimal amount) {
    try {
      TokenHolder holder = new TokenHolder(appKey, secretKey, TokenHolder.ASR_SCOPE);
      holder.refresh();
      String token = holder.getToken();

      String text = "系统到账" + amount + "元";
      // 此处2次urlencode， 确保特殊字符被正确编码
      String params = "tex=" + ConnUtil.urlEncode(ConnUtil.urlEncode(text));
      params += "&per=" + per;
      params += "&spd=" + spd;
      params += "&pit=" + pit;
      params += "&vol=" + vol;
      params += "&cuid=" + cuid;
      params += "&tok=" + token;
      params += "&aue=" + aue;
      params += "&lan=zh&ctp=1";
      System.out.println(url + "?" + params); // 反馈请带上此url，浏览器上可以测试
      HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setConnectTimeout(5000);
      PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
      printWriter.write(params);
      printWriter.close();
      String contentType = conn.getContentType();
      if (contentType.contains("audio/")) {
        byte[] bytes = ConnUtil.getResponseBytes(conn);
        String format = getFormat(aue);
        File file = FileUtil.save("/opt/mp3/", orderNumber + "." + format, bytes);
        String path = AliyunOssFileUtil.uploadPublicFile(file, orderNumber, "mp3/");
        log.info("===成功====>"+path);
        return path;
      } else {
        System.err.println("ERROR: content-type= " + contentType);
        String res = ConnUtil.getResponseString(conn);
        System.err.println(res);
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.info("===合成失败==e==>"+e.getMessage());
    }
    return null;
  }

  // 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav
  private static String getFormat(int aue) {
    String[] formats = {"mp3", "pcm", "pcm", "wav"};
    return formats[aue - 3];
  }

//  public static void main(String[] args) {
//    String path = getMp3("TS32493043294",new BigDecimal("2.40"));
//    System.out.println(path);
//  }
}
